package br.com.nautical.persistence.util;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * Open Session
 * @author panassol
 *
 */
public class PersistenceFilter implements Filter {

	EntityManagerFactory factory;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.factory = Persistence.createEntityManagerFactory("email");

	}
	
	@Override
	public void destroy() {
		this.factory.close();

	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		EntityTransaction transaction = null;
		EntityManager manager = null;
		
		try{
			manager = this.factory.createEntityManager();
			request.setAttribute("EntityManager", manager);
			transaction = manager.getTransaction();
			
			transaction.begin();
			
			chain.doFilter(request, response);
			
			transaction.commit();
			
		} catch (Exception e) {
			
			if(transaction != null && transaction.isActive()){
				transaction.rollback();
			}
			
		} finally {
			
			manager.close();
		}
	}
}
